<?php
namespace Modules\File\Forms\Element;

use Phalcon\Forms\Element\Hidden;

class FileBox extends Hidden
{
    public function ex()
    {
        return array_filter(explode(';', trim($this->getValue(), ';')));
    }

    public static function filterValue($value, $option)
    {
        if (isset($option['maxNum']) && $option['maxNum'] > 1) {
            $output = array();
            if ($value) {
                foreach ($value as $m) {
                    $output[] = $m->value;
                    if (isset($option['valueType']) && $option['valueType'] == 'string') {
                        $output[] = $m->value;
                    } else {
                        $term = $m->term;
                        if ($term) {
                            $output[] = $term->name;
                        }

                    }
                }
                if (!isset($option['valueType']) || $option['valueType'] == 'string') {
                    return implode(';', $output);
                }
                return $output;
            }
        } else {
            if ($value) {
                if ($option['valueType'] == 'id') {
                    return $value->value;
                } else {
                    $term = $value->term;
                    if ($term) {
                        return $term->name;
                    }

                }
            }
        }
        return false;
    }

    public function getValue()
    {
        $value = parent::getValue();
        if (!empty($value)) {
            return $value;
        }
        if (isset($this->_options['autoValue'])) {
            $form = $this->getForm();
            $formData = $form->getData();
            if (!isset($formData[$this->_options['autoValue']])) {
                return '';
            }
            if (!isset($this->_options['valueNum'])) {
                $this->_options['autoNum'] = 0;
            }
            return $this->getImgs($formData[$this->_options['autoValue']], $this->_options['autoNum']);
        }
    }

    public function getImgs($content, $order = 'ALL')
    {
        $pattern = "/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg|\.bmp]))[\'|\"].*?[\/]?>/";
        preg_match_all($pattern, $content, $match);
        if (isset($match[1]) && !empty($match[1])) {
            if ($order === 'ALL') {
                $match[1] = array_slice($match[1], 0, $this->_options['autoNum']);
                return implode(';', $match[1]);
            }
            if (is_numeric($order) && isset($match[1][$order])) {
                return $match[1][$order];
            }
        }
        return '';
    }

    public function render($attributes = null)
    {
        global $di;
        $di->getShared('assets')->addJs('dropzone', '//cdn.bootcss.com/dropzone/4.3.0/dropzone.js', 'footer');
        return parent::render($attributes); // TODO: Change the autogenerated stub
    }
}
